package helpers;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * Simple reusable listening service.
 * @author psyomn
 */

public class UDPListeningService implements Runnable
{
	/**
	 * Looping killer
	 */
	private boolean mTerminated = false;
	
	/**
	 * last return value of listen
	 */
	private String mRet;
	
	/** Socket handle */ 
	private DatagramSocket mSocketHandle; 
	
	/** Port to listen to */
	private int mPort; 
	
	/** 
	 * Default constructor. 
	 * @param port is the port to start the service
	 * listening at. 
	 */
	public UDPListeningService(int port, String msg)
	{
		mPort = port; 
		
		mRet = msg;
		
		try
		{	
			mSocketHandle = new DatagramSocket(port);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println(
					this.getClass().getName() 
					+ ": " 
					+ e.getMessage());
		}
	}
	
	@Override
  public void run()
  {
	  byte[] receiveData = new byte[100];
		DatagramPacket p; 
		String tostr; 
		
	  while(!mTerminated)
	  {
	  	try
	  	{
	  		System.out.println("[BxOff:"+mPort+"] listening...");
	  		p = new DatagramPacket(receiveData, receiveData.length); 
	  		mSocketHandle.receive(p);
	  		tostr = new String(receiveData);
	  		System.out.println("Received: " + tostr);
	  		mRet = tostr; 
	  	}
	  	catch(Exception e)
	  	{
	  		System.out.println(
	  				this.getClass().getName()
	  				+ ":"
	  				+ e.getMessage());
	  	}
	  }
  }
	
	/**
	 * Return the current value. This is not advisable but
	 * go ahead if you're feeling creative!
	 * @return
	 */
	public String getCurVal()
	{
		return mRet; 
	}

}
